﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Xml;
using System.ServiceModel;
using System.ServiceModel.Web;
using Tracy.Plugins.DownloadAdapters.ServiceDefinition;
using System.ServiceModel.Channels;
using Tracy.DataModel;
using System.Collections.Specialized;
using Microsoft.Win32;
using System.IO;
using System.Diagnostics;
using Tracy.DataModel.DownloadAdapter;
using Tracy.DataModel.Config;
using Tracy.Plugins.DownloadAdapters.Model;

namespace Tracy.Plugins.DownloadAdapters
{
    public partial class UTorrentAdapter : IDownloadAdapter, IConfigurable
    {
        private string _applicationFullPath;
        bool _utorrentInstalled = false;

        private object _lockHelper = new object();

        UTorrentWebUIClient _utClient = new UTorrentWebUIClient();

        public UTorrentAdapter()
        {
            CheckRegistry();
        }

        private void CheckRegistry()
        {
            RegistryKey regdir = Registry.ClassesRoot.OpenSubKey("Applications", false);
            regdir = regdir.OpenSubKey("uTorrent.exe", false);
            if (regdir != null)
            {
                regdir = regdir.OpenSubKey("shell").OpenSubKey("open").OpenSubKey("command");

                object installPath = regdir.GetValue("");
                if (installPath != null)
                {
                    _applicationFullPath = installPath.ToString();
                    _applicationFullPath = _applicationFullPath.Substring(1, _applicationFullPath.Length - 7);
                    if (File.Exists(_applicationFullPath)) _utorrentInstalled = true;
                }
            }
        }


        //bool _initFailedFlag = false;
        private void InitClient(string defaultPath)
        {

            if (IsAvailable()) //&& !_initFailedFlag)
            {
                if (Process.GetProcessesByName("uTorrent").Length == 0)
                {
                    Process.Start(_applicationFullPath);
                    bool started = false;
                    for (int i = 0; i < 10; i++)
                    {
                        System.Threading.Thread.Sleep(1000);
                        if (Process.GetProcessesByName("uTorrent").Length > 0)
                        {
                            started = true;
                            break;
                        }
                    }
                    if (!started) throw new InvalidOperationException("Failed to launch uTorrent.");
                }

                //try
                //{

                _utClient.LoadConfig(_currentConfig);
                _utClient.SetDefaultPath(defaultPath);
                
                //}
                //catch
                //{
                //    _initFailedFlag = true;
                //    throw;
                //}
            }
        }


        public void Download(Resource res, string defaultPath)
        {
            if (IsResourceTypeSupported(res.GetResourceType()))
            {
                if (!_utClient.Connected)
                {
                    lock (_lockHelper)
                    {
                        if (!_utClient.Connected)
                        {
                            InitClient(defaultPath);//TODO:error handling
                        }
                    }
                }
                if (IsAvailable())
                {
                    _utClient.Download(res);
                }
            }
        }

        public bool IsAvailable()
        {
            return _utorrentInstalled && (_currentConfig != null);
        }

        public bool IsResourceTypeSupported(string type)
        {
            if (IsAvailable())
            {
                if (type == "BT") return true;
            }
            return false;
        }

        public string[] GetTempFileExts(string type)
        {
            return new string[] { ".!ut" };
        }

        public string GetTempDownloadFolder(string preferredFolder, MediaFile file)
        {
            return preferredFolder;
        }

        public string GetValidFileName(string fileName)
        {
            if (fileName == null) return null;
            return fileName.Replace("?", "_").Replace("\\", "_").Replace("/", "_").Replace("*", "_").Replace("\"", "_").Replace(":", "_").Replace("<", "_").Replace(">", "_");
        }

    }
}
